package com.photoeditor.demo.ui.adapter;

import android.content.pm.PackageManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.photoeditor.demo.app.BaseRecycleViewAdapter;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.ui.widget.FontListItem;

import java.lang.ref.WeakReference;

/**
 * Created by winn on 17/10/17.
 */

public class FontAdapter extends BaseRecycleViewAdapter<StoreOnlineBean> {

    private int mSelIndex = 0;
    private WeakReference<View> mCurSelView;

    private boolean mScaleSelView;

    @Override
    protected RecyclerView.ViewHolder createVHolder(ViewGroup parent, int viewType) {
        Holder holder = new Holder(new FontListItem(parent.getContext()));
        return holder;
    }

    @Override
    protected void showItemView(RecyclerView.ViewHolder holder, int position) throws PackageManager.NameNotFoundException {
        Holder myHolder = (Holder) holder;
        StoreOnlineBean bean = getData().get(position);
        ((FontListItem) myHolder.itemView).updateData(bean, position == mSelIndex);
        if (position == mSelIndex) {
            mCurSelView = new WeakReference<>(myHolder.itemView);
            if (mScaleSelView) {
                myHolder.itemView.setScaleX(1.1f);
                myHolder.itemView.setScaleY(1.1f);
            }
        } else if (mScaleSelView) {
            myHolder.itemView.setScaleX(1f);
            myHolder.itemView.setScaleY(1f);
        }
    }

    @Override
    public long getAdapterItemId(int position) {
        return position;
    }

    public void setSelIndex(int selIndex, View itemView) {
        if (selIndex == mSelIndex) {
            return;
        }
        this.mSelIndex = selIndex;

        if (itemView == null) {
            notifyDataSetChanged();
        } else {
            ((FontListItem) itemView).setSel(true);
            if (mCurSelView != null && mCurSelView.get() != null) {
                ((FontListItem) mCurSelView.get()).setSel(false);
                mCurSelView.get().setScaleX(1);
                mCurSelView.get().setScaleY(1);
            }
            mCurSelView = new WeakReference<>(itemView);
        }
    }

    public void setScaleSelView(boolean scaleSelView) {
        this.mScaleSelView = scaleSelView;
    }

    private class Holder extends RecyclerView.ViewHolder {

        public Holder(View itemView) {
            super(itemView);
        }
    }
}
